<template>
  <van-pull-refresh
    v-model="isRefreshing"
    @refresh="refreshFilmList"
    v-if="filmList.length > 0"
  >
    <van-list
      v-model="isLoading"
      :finished="isFinished"
      finished-text="我是有底线的"
      :offset="100"
      :immediate-check="false"
      @load="loadingFilmList"
    >
      <ul
        class="film-list"
        v-for="(film, index) in filmList"
        :key="film.filmId"
      >
        <li
          class="film-list-item"
          @click="$router.push(`/film/${film.filmId}`)"
        >
          <ul>
            <li class="film-img">
              <img :src="film.poster" :alt="film.name" />
            </li>
            <li class="film-info">
              <ul>
                <li class="film-title">
                  {{ film.name }}<span>{{ film.filmType.name }}</span>
                </li>
                <li class="film-grade" v-show="type === 1">
                  观众评分<span>{{ film.grade ? film.grade : "无" }}</span>
                </li>
                <li class="film-actors">
                  主演：{{ formatActors(film.actors) }}
                </li>
                <li class="film-nation-runtime">
                  {{ detailList[index] }}
                </li>
                <li class="film-premiere-time" v-show="type === 2">
                  上映日期：{{ formatDate(film.premiereAt * 1000) }}
                </li>
              </ul>
            </li>
            <li
              class="btn"
              :class="btnColor"
              v-if="film.isPresale"
              @click.stop="$router.push(`/film/${film.filmId}/cinemas`)"
            >
              {{ btnText }}
            </li>
          </ul>
        </li>
      </ul>
    </van-list>
  </van-pull-refresh>
</template>
<script>
/* vant组件 */
import { List, PullRefresh } from "vant";
/* vux保存的数据 */
import { mapState } from "vuex";
/* 导入http请求和格式化插件 */
import { http, load, formatDate, random } from "@/utils";
export default {
  name: "FilmList",
  /* vantui */
  components: {
    [List.name]: List,
    [PullRefresh.name]: PullRefresh,
  },
  props: {
    /*接收父组件是热映和上映 */
    type: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      filmList: [], //电影列表
      pageNum: 1, //页数
      total: 0, //每页个数
      isLoading: false, // 是否正在加载中
      isFinished: false, // 是否全部加载完成
      isRefreshing: false, // 是否处于下拉刷新状态
    };
  },
  computed: {
    /* 获取城市的id */
    ...mapState("CityModule", ["cityId"]),
    /* 根据上映热映动态显示购票和预购 */
    btnText() {
      return this.type === 1 ? "购票" : "预购";
    },
    /* 根据上映热映动态显示购票和预购按钮 */
    btnColor() {
      return this.type === 1 ? "buy-btn" : "pre-btn";
    },
    // 将详情信息计算成数组
    detailList() {
      const arr = [];
      this.filmList.forEach((film) => {
        const nation = film.nation ? film.nation : "未知地区";
        const runtime = film.runtime ? film.runtime : "--";
        arr.push(`${nation} | ${runtime}分钟`);
      });
      return arr;
    },
  },
  methods: {
    // 加载电影列表
    loadingFilmList() {
      // 若数据全部加载完成，且不是下拉刷新状态，设置 isFinished 属性为 true
      if (
        this.filmList.length >= this.total &&
        this.filmList.length !== 0 &&
        this.isRefreshing === false
      ) {
        this.isFinished = true;
        this.isLoading = false;
        return;
      }
      this.pageNum++;
      http({
        url: `/gateway?cityId=${this.cityId}&pageNum=${
          this.pageNum
        }&pageSize=10&type=${this.type}&k=${random()}`,
        headers: { "X-Host": "mall.film-ticket.film.list" },
      })
        .then((res) => {
          // 如果处于下拉刷新状态 清空列表数据，重置加载状态，重新加载数据
          if (this.isRefreshing) {
            this.filmList = [];
            this.isRefreshing = false;
          }
          // 追加电影列表到现有数组
          this.filmList = [...this.filmList, ...res.data.data.films];
          // 再执行一次检查，如果 this.filmList 的初始长度就是0，则不再加载数据
          if (this.filmList.length === 0) {
            this.isFinished = true;
          }
          this.total = res.data.data.total;
          // 加载完成后，调置 isLoading 为 false
          this.isLoading = false;
        })
        .catch((err) => {
          console.warn(err);
          this.isLoading = false;
        });
    },
    // 下拉刷新时，清空列表数据，重置加载状态，重新加载数据
    refreshFilmList() {
      this.isFinished = false;
      this.isLoading = true;
      this.pageNum = 0;
      this.loadingFilmList();
    },
    // 格式化演员名单
    formatActors(actors) {
      if (typeof actors !== "object") return "暂无主演";
      return actors.map((actor) => actor.name).join(" ");
    },
    // 格式化日期
    formatDate(milliseconds) {
      return formatDate(milliseconds);
    },
  },
  mounted() {
    load({
      url: `/gateway?cityId=${this.cityId}&pageNum=${
        this.pageNum
      }&pageSize=10&type=${this.type}&k=${random()}`,
      headers: { "X-Host": "mall.film-ticket.film.list" },
    })
      .then((res) => {
        this.filmList = res.data.data.films;
        this.total = res.data.data.total;
      })
      .catch((err) => {
        console.warn(err);
      });
  },
};
</script>
<style lang="scss" scoped>
.film-list-item {
  border-top: 2px solid #f9f9f9;
  cursor: pointer;
}
.film-list-item > ul {
  display: flex;
  padding: 15px;
  align-items: center;
  .film-img {
    width: 66px;
    height: 94px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .film-info {
    width: calc(100% - 136px); // 自动计算宽度
    height: 94px;
    margin: 0px 10px;
    font-size: 13px;
    color: #797d82;
    ul {
      height: 100%; // 必须指定，否则 justify-content 不生效
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
    }
    .film-title {
      font-size: 16px;
      color: #191a1b;
      display: flex;
      align-items: center;
      span {
        font-size: 9px;
        color: #fff;
        background-color: #d2d6dc;
        height: 14px;
        line-height: 14px;
        padding: 0 2px;
        border-radius: 2px;
        margin-left: 5px;
      }
    }
    .film-grade span {
      font-size: 14px;
      color: #ffb232;
      margin-left: 5px;
    }
    li {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .btn {
    width: 50px;
    height: 25px;
    font-size: 13px;
    text-align: center;
    line-height: 25px;
    border: 1px solid;
    border-radius: 3px;
    background: white;
  }
  .buy-btn {
    color: #ff5f16;
  }
  .pre-btn {
    color: #ffb232;
  }
}
</style>
